package net.maku.framework.beansearcher;

import cn.zhxu.bs.BeanMeta;
import cn.zhxu.bs.IllegalParamException;
import cn.zhxu.bs.ParamFilter;
import cn.zhxu.bs.util.MapUtils;
import cn.zhxu.bs.util.StringUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 排序字段参数转换处理
 * 前端的排序参数是 order 与 asc
 * Bean Searcher 的排序参数是 sort 与 order
 * @author Troy.Zhou
 */
@Component
@AllArgsConstructor
public class OrderAscParamFilter implements ParamFilter {

    @Override
    public <T> Map<String, Object> doFilter(BeanMeta<T> beanMeta, Map<String, Object> paraMap) throws IllegalParamException {
        var order = paraMap.get("order");
        var asc = paraMap.get("asc");
        if (order instanceof String orderField && asc instanceof String ascStr &&
                StringUtils.isNotBlank(orderField) && StringUtils.isNotBlank(ascStr)) {
            var isAsc = Boolean.parseBoolean(ascStr);
            return MapUtils.builder(paraMap)
                    .orderBy(orderField).asc(isAsc).desc(!isAsc)
                    .build();
        }
        return paraMap;
    }

}
